package com.lifl.b328.garden.model;

import java.io.File;
import java.nio.charset.Charset;
import java.util.Observer;

import org.apache.http.Header;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.mime.HttpMultipartMode;
import org.apache.http.entity.mime.MultipartEntity;
import org.apache.http.entity.mime.content.FileBody;
import org.apache.http.entity.mime.content.StringBody;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.protocol.BasicHttpContext;
import org.apache.http.protocol.HttpContext;
import org.json.JSONObject;

public class SendJSONTask extends HttpAsyncTask<String, JSONObject>{
	protected Observer observer;
	
	public SendJSONTask(Observer obs) {
		this.observer = obs;
	}

	@Override
	//params : 0->serveur, 1->Json 2-> photo
	protected JSONObject doInBackground(String... params) {
		this.addObserver(observer);
		HttpClient httpclient;
		try{
			HttpPost httppost = new HttpPost(params[0]);
			httpclient = new DefaultHttpClient();
			HttpContext localcontext = new BasicHttpContext();
			MultipartEntity mpe= new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE);
			mpe.addPart("json", new StringBody(params[1],"text/plain",Charset.forName( "UTF-8" )));
			System.out.println("params length "+params.length);
			
			if(params.length > 2 && !params[2].equals(""))
			{
				System.out.println(params[2]);
				File f = new File(params[2]);
				if(f.isFile())	
					mpe.addPart("pictures", new FileBody(f,"image/jpeg"));
			}

			httppost.setEntity(mpe);
			System.out.println("envoie");
			System.out.println(mpe.isStreaming());
			System.out.println("Qt headers: "+httppost.getAllHeaders().length);
			for (Header h : httppost.getAllHeaders()) {
				System.out.println(h.toString());
			}
			HttpResponse httpresponse = httpclient.execute(httppost, localcontext);
			System.out.println("envoyer");
			String res = HttpAsyncTask.getStringContent(httpresponse);
			System.out.println("reponse : " +res);
			JSONObject json_data = new JSONObject(res);
			return json_data;
		}
		catch( Exception e)
		{
			e.printStackTrace();
		}
		return null;
	}
	
	protected void onPostExecute(JSONObject result) {
		this.ringListeners(result);
	};
}
 